package com.itcam.search.listener;

import com.alibaba.fastjson.JSON;
import com.itcam.common.constants.ArticleConstants;
import com.itcam.model.search.vos.SearchArticleVo;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class SyncArticleListener {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void onMessage(String message){
        // 检查消息是否非空，以防止处理空消息
        if(StringUtils.isNotBlank(message)){

            // 记录接收到的消息，用于调试和审计
            log.info("SyncArticleListener,message={}",message);

            // 将消息解析为SearchArticleVo对象，以便后续操作
            SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);

            // 创建一个索引请求，指定索引名为"app_info_article"
            IndexRequest indexRequest = new IndexRequest("app_info_article");

            // 设置文档ID为SearchArticleVo对象的ID
            indexRequest.id(searchArticleVo.getId().toString());

            // 设置文档内容为消息，格式为JSON
            indexRequest.source(message, XContentType.JSON);

            // 尝试将文档索引到Elasticsearch中
            try {
                restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                // 如果发生IOException，打印堆栈跟踪并记录错误
                e.printStackTrace();
                log.error("sync es error={}",e);
            }
        }

    }

}